package com.chixigua.chaos.utils;

import com.alibaba.fastjson.JSONObject;

import java.io.Serializable;

/**
 * 用于封装AJAX调用以后的JSON返回值
 * 其中正确返回值:
 *  {state:0, data:返回数据, message:错误消息}
 * 错误返回值:
 *  {state:1, data:null, message:错误消息}
 */
public class JsonResult implements Serializable {
    private static final long serialVersionUID = -3644950655568598241L;

    public static final int SUCCESS=200;
    public static final String SUCCESS_MSG = "请求成功";
    public static final int ERROR=1;

    /**
     * 返回是否成功的状态, 0表示成功,
     * 1或其他值 表示失败
     */
    private int code;
    /**
     * 成功时候,返回的JSON数据
     */
    private Object data;
    /**
     * 是错误时候的错误消息
     */
    private String msg;



    public JsonResult() {
    }


    public JsonResult(int code, Object data, String msg) {
        this.code = code;
        this.data = data;
        this.msg = msg;

    }

    public JsonResult(Throwable e){
        code = ERROR;
        data=null;
        msg=e.getMessage();

    }

    public JsonResult(Object data){
        code = SUCCESS;
        this.data=data;
        msg="";

    }




    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    @Override
    public String toString() {
        return "JsonResult{" +
                "code=" + code +
                ", data=" + data +
                ", msg='" + msg + '\'' +
                '}';
    }


    /**
     * 返回一个returnData为空对象的成功消息的json
     *
     * @return
     */
    public static JSONObject successJson() {
        return successJson(new JSONObject());
    }

    /**
     * 返回一个返回码为100的json
     *
     * @param returnData json里的主要内容
     * @return
     */
    public static JSONObject successJson(Object returnData) {
        Common.getObjDefault(returnData);
        JSONObject resultJson = new JSONObject();
        resultJson.put("code", SUCCESS);
        resultJson.put("msg", SUCCESS_MSG);
        resultJson.put("data", returnData);
        return resultJson;
    }

    /**
     * 返回错误信息JSON
     *
     * @param errorEnum 错误码的errorEnum
     * @return
     */
    public static JSONObject errorJson(ErrorEnum errorEnum) {
        JSONObject resultJson = new JSONObject();
        resultJson.put("code", errorEnum.getErrorCode());
        resultJson.put("msg", errorEnum.getErrorMsg());
        resultJson.put("data", new JSONObject());
        return resultJson;
    }

}
